package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.*;
import com.itheima.common.PageParam;
import com.itheima.dao.OrderDao;
import com.itheima.dto.OrdersDto;
import com.itheima.service.*;
import com.itheima.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private HttpSession session;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;


    @Override
    public IPage<Orders> findpage(PageParam pageParam){
//1.构建分页对象

        IPage<Orders> p =new Page<>(pageParam.getPage(),pageParam.getPageSize());
        //2.构建条件对象
        LambdaQueryWrapper<Orders> lqw =new LambdaQueryWrapper<>();
        //3.追加条件
        lqw.like(pageParam.getNumber()!=null,Orders::getNumber,pageParam.getNumber());
        lqw.ge(pageParam.getBeginTime()!=null,Orders::getOrderTime,pageParam.getBeginTime());
        lqw.le(pageParam.getEndTime()!=null,Orders::getCheckoutTime,pageParam.getEndTime());
        //执行查询
        return orderDao.selectPage(p,lqw);

    }


    /**
     * 提交订单
     *   1. 提交订单其实是一种添加的行为，但是它要往两张表里面添加数据： orders 和 order_detail
     *
     *   2. 先添加 orders 表、
     *      2.1 才能得到订单的id主键
     *
     *   3. 再添加order_detail 表
     *      3.1 给订单详情设置 订单id主键
     *
     * @param order
     * @return
     */
    @Override
    public int add(Orders order) {
        //1. 先添加订单表

        //1.1 设置订单号
        // 获取用户信息
        User user = (User) session.getAttribute("user");

        //获取地址信息
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());

        order.setNumber(UUID.randomUUID().toString().replace("-" , ""));
        //1.2 设置状态值 : 1 : 未付款，2： 已付款，待派送 ...
        order.setStatus(1);
        //1.3 设置用户id
        order.setUserId(user.getId());
        //1.4 设置地址id【页面提供了，不需要设置】
        //1.5 设置下单时间
        order.setOrderTime(LocalDateTime.now());
        //1.6 设置支付时间
        order.setCheckoutTime(LocalDateTime.now());
        //1.7 设置支付方式【页面提供了，不需要设置】
        //1.8 设置总金额 【页面提供了，不需要设置】
        //1.9 设置备注【页面提供了，不需要设置】
        //1.10 设置收货电话
        order.setPhone(addressBook.getPhone());
        //1.11 设置收货地址
        String address = ( addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "" )
                + ( addressBook.getCityName() != null ? addressBook.getCityName() : "" )
                + ( addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "" )
                + ( addressBook.getDetail() != null ? addressBook.getDetail() : "" );
        order.setAddress(address);

        //1.12 设置下单的用户名称
        order.setUserName(user.getName());
        //1.13 设置收货人名称
        order.setConsignee(addressBook.getConsignee());

        //1.1 补充数据
        //1.2 执行添加
        int row1 = orderDao.insert(order);

        //2. 再添加订单详情表 :: 详情表的数据，页面没有提供，购买的详细内容，其实就是购物车的内容。

        //2.1 获取当前用户的购物车数据
        List<ShoppingCart> cartList = shoppingCartService.list();
        int row2 = 0 ;
        if(cartList != null && cartList.size() >  0){
            //2.2 遍历每一个购物车数据
            for (ShoppingCart shoppingCart : cartList) {

                //2.3 遍历一次，构建一个订单详情对象！
                OrderDetail orderDetail = new OrderDetail();


                //2.4 把购物车的数据拷贝到订单详情对象
                BeanUtils.copyProperties(shoppingCart , orderDetail);

                //2.5 设置订单id
                orderDetail.setOrderId(order.getId());

                //2.6 添加到订单详情表
                row2 += orderDetailService.add(orderDetail);

            }
            return row2 == cartList.size() ? 1 : 0;
        }

        return row1;
    }

    /**
     * 最新订单查看
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<OrdersDto> newestOrder(PageParam pageParam) {

        IPage<Orders> p = new Page<>(pageParam.getPage(), pageParam.getPageSize());

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        lqw.orderByDesc(Orders::getOrderTime);
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());

        IPage<Orders> ordersIPage = orderDao.selectPage(p, lqw);

        List<OrdersDto> ordersDtoList = ordersIPage.getRecords().stream().map(orders -> {

            OrdersDto ordersDto = new OrdersDto();

            BeanUtils.copyProperties(orders, ordersDto);
            List<OrderDetail> orderDetailList = orderDetailService.findById(orders.getId());
            ordersDto.setOrderDetails(orderDetailList);

            return ordersDto;

        }).collect(Collectors.toList());

        IPage<OrdersDto> ordersDtoIPage = new Page<>();
        BeanUtils.copyProperties(ordersIPage,ordersDtoIPage);
        ordersDtoIPage.setRecords(ordersDtoList);
        //ordersDtoIPage.setTotal(ordersIPage.getTotal());

        return ordersDtoIPage;

    }

    @Override
    public int paisong(Orders order) {
        return orderDao.updateById(order);
    }
}
